package com.lv.handler;

import cn.hutool.json.JSONUtil;
import com.lv.common.AjaxResult;
import com.lv.common.untils.TokenUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * 登陆成功处理器
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/07/19:51
 * @Description:
 */
@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    TokenUntil tokenUntil;
    @Value("${jwt.header}")
    private String header;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream=response.getOutputStream();
        //生成jwt 放置到请求头中
        String token = tokenUntil.createToken(authentication.getName());
        response.setHeader(header,token);
        AjaxResult success = AjaxResult.success("登录成功！");
        outputStream.write(JSONUtil.toJsonStr(success).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
